package com.xiaolin.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @ClassName HttpClientUtils
 * @Description TODO
 * @Detail 使用httpclient封装post和get请求
 * @Author MyPC
 * @Date 2020/9/30
 * @Version 1.0
 */
public class HttpClientUtils {
    /**
     * get请求
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl){
        //HttpClient 客户端
        CloseableHttpClient httpClient=null;
        //HttpClient 响应对象
        CloseableHttpResponse response=null;
        //响应结果
        String result="";
        try {
            //1、创建httpclient 客户端
            httpClient = HttpClients.createDefault();
            //2、创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(httpUrl);
            //3、设置请求头信息，用于鉴权
            //4、配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000 * 15)
                    .setConnectionRequestTimeout(1000 * 15)
                    .setSocketTimeout(1000 * 15)
                    .build();
            //5、设置requestConfig 配置实例
            httpGet.setConfig(requestConfig);
            //6、执行get请求获取响应结果
            response=httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result=EntityUtils.toString(entity,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(response !=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient!=null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * post请求
     * @param httpUrl
     * @param params
     * @return
     */
    public static String doPost(String httpUrl,Map<String,Object> params){
        //HttpClient 客户端
        CloseableHttpClient httpClient=null;
        //HttpClient 响应对象
        CloseableHttpResponse response=null;
        //响应结果
        String result="";
        httpClient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(httpUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000 * 15)
                .setConnectionRequestTimeout(1000 * 15)
                .setSocketTimeout(1000 * 15)
                .build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type",  "application/x-www-form-urlencoded");
        if(params!=null && params.size() >0){
            List<NameValuePair> valuePairs=new ArrayList<>();
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()){
                Map.Entry<String, Object> mapEntry = iterator.next();
                valuePairs.add(new BasicNameValuePair(mapEntry.getKey(),mapEntry.getValue().toString()));
            }
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(valuePairs,"utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
